<script setup lang="ts">
import { useI18n } from "vue-i18n";
import { WalletAxios } from "@/api";
import { ref, reactive, onMounted, watch } from "vue";
import { FiltrationFun } from "@/utils";
import sortBy from "lodash";
import { BANTypeImg } from "@/utils";
import { Popup, showFailToast } from "vant";
import { UserStore } from "@/store";
const userStore = UserStore();
const { t } = useI18n();
const selectIndex = ref(0);
const joinAct = ref(false);
//选择类型
const getSelect = index => {
  selectIndex.value = index;
};
//通道下标
const aisleIndex = ref(0);
const selectAisle = index => {
  aisleIndex.value = index;
};
const paylist: any = reactive({ rechargeAmounts: [] });
onMounted(() => {
  //获取充值金额列表
  getRechargeConfigList();
  //获取支付类型
  getEpayPaymentMethods();
  //进入充值页面
  FiltrationFun.setReportEvent("AddToCart");
});
const methodsList: any = ref([
  {
    bank: "",
    bankCode: [],
  },
]);
const rechargeMin = ref(0);
const rechargeMax = ref(0);
//获取支付类型
const getEpayPaymentMethods = () => {
  WalletAxios.getEpayPaymentMethods().then(res => {
    methodsList.value = res.paymentMethod.rechargeBanks;
    rechargeMin.value = res.paymentMethod.rechargeMin;
    rechargeMax.value = res.paymentMethod.rechargeMax;
  });
};
//参加活动的充值列表
const giftConfigsList: any = ref([]);
//获取充值金额列表
const getRechargeConfigList = () => {
  WalletAxios.getRechargeConfigList().then(res => {
    res.rechargeAmounts.sort((a, b) => a - b);
    res.rechargeAmounts.filter(item => {
      const val = item / 100;
      paylist.rechargeAmounts.push(val);
    });
    res.giftConfigs.sort((a: any, b: any) => a.rechargeAmount - b.rechargeAmount);
    res.giftConfigs.filter((item: any) => {
      item.rechargeAmount = item.rechargeAmount / 100;
      item.handselRatio = item.handselRatio;
    });
    giftConfigsList.value = res.giftConfigs;
  });
};
const inputVal: any = ref("");
//赠送的钱
//const giveaway=ref(0);
//选择钱
const getSelectMoney = res => {
  inputVal.value = inputVal.value === res ? 0 : Number(res);
};
//开启充值页面页面
const popupShow = ref(false);
//充值连接
const paymentImg = ref("");
//充值
const clickTopup = sortBy.throttle(() => {
  if (!userStore.isLogin) {
    showFailToast(t("tip.notLogin"));
    return false;
  }
  const bank = methodsList.value[selectIndex.value].bank;
  const bankCode = methodsList.value[selectIndex.value].bankCode[aisleIndex.value];
  if (inputVal.value >= rechargeMin.value / 100 && inputVal.value <= rechargeMax.value / 100) {
    WalletAxios.createEpayRechargePaymentOrder({
      bank: bank,
      bankCode: bankCode,
      currencyAmount: ensureTwoDecimalPlaces(inputVal.value),
      giftStatus: joinAct.value ? 1 : 0,
    }).then(res => {
      paymentImg.value = res.payUrl;
      popupShow.value = true;
      //充值拉单成功
      FiltrationFun.setReportEvent("InitiateCheckout");
    });
  } else {
    showFailToast(t("redRain.moneyMsg"));
  }
}, 1000);
function ensureTwoDecimalPlaces(num) {
  // 将数字转换为字符串
  let numStr = num.toString();

  // 检查是否有小数点
  if (numStr.includes(".")) {
    // 获取小数部分的长度
    const decimalPart = numStr.split(".")[1];
    const decimalLength = decimalPart.length;

    // 如果小数部分长度小于2，则补足两位
    if (decimalLength < 2) {
      return parseFloat(numStr + "0".repeat(2 - decimalLength)).toFixed(2);
    } else {
      // 如果已经有两位或更多小数位，直接返回
      return numStr;
    }
  } else {
    // 如果没有小数部分，直接补足两位
    return parseFloat(numStr + ".00").toFixed(2);
  }
}
const joinActFun = () => {
  joinAct.value = joinAct.value ? false : true;
  if (joinAct.value) {
    discountMoney.value = calculateBonus(inputVal.value);
  } else {
    discountMoney.value = 0;
  }
};
//保留两位小数
function resultFun(num) {
  return Math.trunc(num * 100) / 100;
}
//输入的值
watch(
  [() => inputVal.value],
  newValue => {
    if (joinAct.value) {
      discountMoney.value = calculateBonus(newValue[0]);
    }
  },
  { deep: true },
);

//折扣的钱
const discountMoney = ref(0);
//计算折扣函数
// function calculateBonus(num) {
//   console.log("返回是什么", giftConfigsList.value);
//   if (typeof num === "number" && !isNaN(num)) {
//     const sortedConfigs = giftConfigsList.value.sort((a, b) => a.rechargeAmount - b.rechargeAmount);
//     // 遍历 giftConfigs 判断 num 的区间
//     for (let config of sortedConfigs) {
//       const rechargeAmount = config.rechargeAmount;
//       const handselRatio = config.handselRatio; // 除以 1000
//       if (num <= rechargeAmount) {
//         // 当前 num 小于 rechargeAmount，返回 handselRatio * rechargeAmount
//         return toFixedNoRound((handselRatio / 100) * rechargeAmount, 3);
//       }
//     }
//   }
//   // 如果 num 小于最小的 rechargeAmount，返回 0//1000021
//   return 0;
// }
function calculateBonus(num) {
  if (typeof num === "number" && !isNaN(num)) {
    // 按 `rechargeAmount` 排序
    const sortedConfigs = giftConfigsList.value.sort((a, b) => a.rechargeAmount - b.rechargeAmount);

    // 遍历找到小于等于 `num` 的最大 `rechargeAmount`
    let applicableConfig = null;
    for (let config of sortedConfigs) {
      if (num >= config.rechargeAmount) {
        applicableConfig = config; // 更新适用配置
      } else {
        break; // 由于是排序的，后续的值都会更大，直接退出
      }
    }

    if (applicableConfig) {
      // 计算折扣值
      const { rechargeAmount, handselRatio } = applicableConfig;
      return toFixedNoRound((handselRatio / 100) * rechargeAmount, 3);
    }
  }

  // 如果没有找到适用配置或 `num` 无效，返回 0
  return 0;
}
function toFixedNoRound(value, decimals) {
  const strValue = value.toString();
  if (strValue.includes(".")) {
    const [integer, decimal] = strValue.split(".");
    return `${integer}.${decimal.slice(0, decimals)}`;
  }
  return strValue; // 没有小数时，直接返回原值
}
const focusType = ref(false);
//失去焦点
const inputBblur = () => {
  focusType.value = false;
};
//获取焦点
const inputFocus = () => {
  focusType.value = true;
};
</script>
<template>
  <div>
    <!-- 孟加拉充值页面 -->
    <div class="frame-div">
      <div class="ranndom-container">
        <div class="title-frame df ai-center">
          {{ t("recharge.depositMethod") }}
        </div>
        <div class="show-more-container df ai-center">
          <div
            class="change-item-animate-frame"
            :class="{ 'select-animate': index == selectIndex }"
            v-for="(item, index) in methodsList"
          >
            <div
              class="change-item-animate df ai-center jc-center"
              :key="index"
              :class="[index == 4 ? 'right0' : '', index == selectIndex ? 'select-index' : '']"
              @click="getSelect(index)"
            >
              <div>
                <img :src="BANTypeImg(item.bank)" />
                <div class="vcn-list-text" :class="[index == selectIndex ? 'select-text' : '']">
                  {{ item.bank.substr(4) }}
                </div>
              </div>
              <div class="select-frame" v-show="index == selectIndex"></div>
            </div>
          </div>
        </div>
        <div class="wysiwyg-frame df ai-center">
          <img src="@/image/new_img/home/user_img/tips_jianbain.png" />
          <div>{{ t("recharge.depositMethodTitle") }}</div>
        </div>
      </div>

      <div class="content-radius-frame">
        <div class="radius-frame">
          <div class="ranndom-container-frame">
            <div class="title-frame df ai-center">
              {{ t("recharge.paymentChannels") }}
            </div>
            <div class="aisle-frame df fw-wrap ai-center">
              <div
                class="aisle-content df ai-center jc-center"
                v-for="(item, index) in methodsList[selectIndex].bankCode"
                :name="item"
                :key="index"
                :class="[aisleIndex == index ? 'aisle-true' : '']"
                @click="selectAisle(index)"
              >
                {{ t("recharge.aisle") }} {{ index + 1 }}
              </div>
            </div>
          </div>
          <div class="promotionsAct-frame">
            <div class="df ai-center atcframe">
              <div
                v-show="!joinAct"
                class="attend-event df ai-center jc-center"
                @click="joinActFun"
              ></div>
              <img
                @click="joinActFun"
                v-show="joinAct"
                class="attend-img"
                src="@/image/new_img/home/user_img/icon_checkbox_2.svg"
              />
              <div class="promotionsAct-text">{{ t("recharge.promotionsAct") }}</div>
            </div>
            <div>
              <div class="recharge-instructions-frame">
                <div class="recharge-instructions df ai-center">
                  <img
                    class="tips-jianbain"
                    src="@/image/new_img/home/user_img/tips_jianbain.png"
                  />
                  {{ t("userSet.rechargeInstructions") }}
                </div>
              </div>
            </div>
          </div>
          <!-- <div class="wysiwyg-frame">
            <div>{{ t("recharge.depositMethodTitle") }}</div>
          </div> -->
          <div
            class="input-frame df ai-center jc-space-between"
            :class="{ 'focus-input': focusType }"
          >
            <div class="left-frame df ai-center">
              <div class="title-frame2">
                {{ t("currencyType.pt") }}
              </div>

              <div class="field-class">
                <input
                  class="field-class-frame1"
                  type="number"
                  v-model.number="inputVal"
                  :placeholder="
                    t('inputPlaceholder.rechargePlaceholder') +
                    `(${rechargeMin / 100} ~ ${rechargeMax / 100})`
                  "
                  @focus="inputFocus"
                  @blur="inputBblur"
                />
              </div>
            </div>
            <div class="right-frame df ai-center" v-show="joinAct">
              <span class="">{{ t("recharge.extra") }} </span>
              <div class="act-money">+{{ discountMoney }}</div>
            </div>
          </div>
          <div class="select-list-frame" v-show="paylist.rechargeAmounts.length !== 0 && !joinAct">
            <div
              v-for="(item, index) in paylist.rechargeAmounts"
              :key="index"
              class="list-content"
              :class="{ 'select-val-frame ': inputVal == item }"
              @click="getSelectMoney(item)"
            >
              {{ t("currencyType.pt") }} {{ FiltrationFun.formatNumber(item) }}
            </div>
          </div>

          <div class="select-list-frame" v-show="giftConfigsList.length !== 0 && joinAct">
            <div
              v-for="(item, index) in giftConfigsList"
              :key="index"
              class="list-content"
              :class="{ 'select-val-frame ': inputVal == item.rechargeAmount }"
              @click="getSelectMoney(item.rechargeAmount)"
            >
              <div class="item-type1" :class="{ 'select-item': inputVal === item.rechargeAmount }">
                <div class="item-type1-val">{{ resultFun(item.handselRatio) }}%</div>
              </div>
              {{ t("currencyType.pt") }} {{ FiltrationFun.formatNumber(item.rechargeAmount) }}
            </div>
          </div>

          <div
            class="topup-bottom-bonustips df ai-center"
            v-show="giftConfigsList.length > 0 && joinAct"
          >
            <img src="@/image/new_img/home/user_img/deposit_bonus.png" />
            {{ t("recharge.rechargeActText") }}
          </div>

          <div class="bottom-frame">
            <img
              v-show="inputVal > rechargeMax / 100 || inputVal < rechargeMin / 100"
              src="@/image/new_img/home/user_img/btnv2_topup_disable.png"
            />
            <img
              v-show="inputVal >= rechargeMin / 100 && inputVal <= rechargeMax / 100"
              src="@/image/new_img/home/user_img/btnv2_topup_enable.png"
              @click="clickTopup"
            />
          </div>
        </div>
      </div>
    </div>
    <!-- 弹起充值页面 -->
    <Popup
      v-model:show="popupShow"
      :position="'bottom'"
      z-index="10000"
      duration="0.5"
      style="height: 100%; background-color: #1b0a24"
      :overlay="false"
      :safe-area-inset-top="true"
      :safe-area-inset-bottom="true"
    >
      <div class="content-frame2">
        <div class="title-frame df jc-center ai-center">
          <img
            class="close-img"
            src="@/image/new_img/home/cs_close.png"
            @click="popupShow = false"
          />
          <div class="title-name df ai-center">{{ t("userSet.recharge") }}</div>
        </div>
        <div class="payment-frame">
          <iframe class="image-frame" :src="paymentImg"></iframe>
        </div>
      </div>
    </Popup>
  </div>
</template>
<style lang="less" scoped>
.frame-div {
  width: 100%;
  height: 100%;
  background-image: url(@/image/new_img/main_bg_2.png);
  background-size: cover;
  background-repeat: repeat;
  position: relative;
  left: 0;
  top: 0;
  overflow-y: scroll;
  .ranndom-container {
    width: calc(100% - 60px);
    margin: auto;
    height: auto;
    .title-frame {
      width: 100%;
      height: 60px;
      color: #ffffffd9;
      font-size: 28px;
      // &::before {
      //   content: "";
      //   width: 10px;
      //   height: 10px;
      //   display: inline-block;
      //   border-radius: 50%;
      //   background: #fb9e00;
      //   margin-right: 10px;
      // }
    }
    .show-more-container {
      width: 100%;
      height: auto;
      overflow-x: auto;
      &::-webkit-scrollbar {
        display: none;
        overflow: -moz-scrollbars-none; /* Firefox */
        -ms-overflow-style: none; /* IE 和 Edge */
      }
      .change-item-animate-frame {
        width: 154px;
        height: 154px;
        border-radius: 32px;
        box-sizing: border-box;
        padding: 2px;
        margin-right: 10px;
      }
      .select-animate {
        background-image: linear-gradient(to right, #fe7919, #ab3fe7);
      }
      .change-item-animate {
        width: 100%;
        height: 100%;
        border-radius: 32px;
        text-align: center;
        background-color: #3d2f45;

        // border: 1px solid;
        img {
          width: 68px;
          height: 68px;
        }
        .vcn-list-text {
          width: 100%;
          text-align: center;
          font-size: 20px;
          color: rgba(255, 255, 255, 0.3);
          margin-top: 6px;
        }
        .select-text {
          color: #ffffff;
        }
      }

      .select-index {
        // border-image: linear-gradient(to right, #fe7919, #ab3fe7) 1;
        background-image: linear-gradient(
          45deg,
          rgba(254, 121, 25, 0.2) 0%,
          rgba(171, 63, 231, 0.2) 100%
        );
      }

      .right0 {
        margin-right: 0;
      }
      .select-frame {
        position: absolute;
        right: 0;
        width: 32px;
        height: 32px;
        bottom: 0;
        fill: #ab3fe7;
      }
    }
  }
  .wysiwyg-frame {
    width: 100%;
    height: auto;
    padding-top: 10px;
    font-size: 20px;
    line-height: 36px;
    color: rgba(255, 255, 255, 0.45);
    img {
      width: 28px;
      height: 28px;
    }
  }

  .select-list-frame {
    padding: 0;
    width: 100%;
    height: auto;
    /*设置布局方式为flex布局*/
    display: flex;
    /*换行*/
    flex-wrap: wrap;
    margin-top: 30px;
    .list-content {
      width: 214.5px;
      height: 76px;
      margin-right: 20px;
      list-style: none;
      text-align: center;
      line-height: 76px;
      background-color: #ffffff26;
      color: white;
      font-weight: bolder;
      border-radius: 30px;
      margin-bottom: 10px;
      font-size: 24px;
      overflow: hidden;
      position: relative;
    }
    .list-content:nth-child(3n + 0) {
      margin-right: 0;
    }
    .select-val-frame {
      background-color: #ab3fe7;
    }
    .item-type1 {
      position: absolute;
      right: -50px;
      top: -14px;
      width: 104px;
      height: 56px;
      background-color: rgba(254, 121, 25, 1);
      z-index: 2;
      transform: rotate(45deg);
      font-size: 16px;
      .item-type1-val {
        height: 40px;
        color: rgba(0, 0, 0, 0.65);
        margin-top: 8px;
        margin-right: 8px;
      }
    }
    .select-item {
      color: #000000a6;
    }
  }
  .input-frame {
    width: 100%;
    height: 96px;
    border: 1px solid rgba(255, 255, 255, 0.04);
    background-color: rgba(255, 255, 255, 0.04);
    border-radius: 32px;
    .left-frame {
      width: 70%;
      height: auto;
    }
    .title-frame2 {
      color: #ab3fe7;
      font-size: 27px;
      margin-left: 22px;
      font-weight: 700;
    }
    .field-class {
      width: 80%;
      font-size: 27px;
      color: #ffffff !important;
      margin-left: 20px;
    }
  }
  .focus-input {
    border: 1px solid #ab3fe7;
  }
}
.field-class-frame1 {
  width: 100%;
  height: 50px;
  background-color: transparent;
  color: rgba(255, 255, 255, 0.85);
  border: none;
  font-size: 28px;
  line-height: 78px;
}
.field-class-frame1::-webkit-inner-spin-button,
.field-class-frame1::-webkit-outer-spin-button {
  -webkit-appearance: none;
  margin: 0;
}
.field-class-frame1:-moz-placeholder {
  color: #524f62;
  font-size: 28px;
}
.field-class-frame1::-moz-placeholder {
  color: #524f62;
}

.bottom-frame {
  width: auto;
  margin: auto;
  margin-top: 61px;
  text-align: center;
  margin-bottom: 200px;
  img {
    width: 250px;
    height: 100px;
  }
}
// 弹起充值的弹窗
.content-frame2 {
  width: 100%;
  height: calc(100% - 106px);
  /*半透明背景色 */
  backdrop-filter: blur(20px);
  /*背景模糊效果 */
  -webkit-backdrop-filter: blur(20px);

  .title-frame {
    width: 100%;
    height: 105px;
    background: rgba(255, 255, 255, 0.04);
    position: relative;
    left: 0;
    right: 0;

    .title-name {
      font-size: 30px;
      color: #ffffff;
    }
  }

  .close-img {
    width: 55px;
    height: 55px;
    margin-left: 30px;
    position: absolute;
    left: 0;
    top: 30px;
  }

  .payment-frame {
    width: 100%;
    height: 100%;
    overflow: hidden;
  }

  .image-frame {
    width: 100%;
    height: 100%;
  }
}
.promotionsAct-frame {
  width: 100%;
  height: auto;
  margin-top: 30px;
  .attend-event {
    width: 26px;
    height: 26px;
    border-radius: 50%;
    border: 1px solid #fff;
  }
  .attend-img {
    width: 26px;
    height: 26px;
  }
  .promotionsAct-text {
    font-size: 28px;
    color: rgba(255, 255, 255, 0.65);
    margin-left: 10px;
  }
  .border-on {
    //border-color: rgba(255, 255, 255, 0.5);
    border: none;
  }
}
.recharge-instructions-frame {
  width: 98%;
  height: auto;
  border-radius: 10px;
  .recharge-instructions {
    width: 100%;
    height: 66px;
    border-radius: 10px;
    justify-content: flex-start;
    color: rgba(255, 255, 255, 0.45);
    font-size: 23px;
  }
  .tips-jianbain {
    width: 28px;
    height: 28px;
    margin-right: 10px;
  }
  .atcframe {
    margin-bottom: 30px;
  }
}
.topup-bottom-bonustips {
  width: 100%;
  height: 100px;
  border-radius: 34px;
  background-image: linear-gradient(-79deg, #d17eff 0%, #7efffe 100%);
  margin-top: 40px;
  font-size: 24px;
  color: #7800bb;
  img {
    width: 66px;
    height: 66px;
    margin-left: 20px;
  }
}
.right-frame {
  font-size: 28px;
  margin-right: 22px;
  color: #ffffff73;
  .act-money {
    color: #ffffffd9;
    margin-left: 20px;
  }
}
.content-radius-frame {
  width: 100%;
  height: calc(1400px - 316px);
  background: rgba(255, 255, 255, 0.1);
  border-radius: 40px 40px 0px 0px;
  .radius-frame {
    width: calc(100% - 60px);
    height: 100%;
    margin: auto;
  }
  .ranndom-container-frame {
    width: 100%;
    height: auto;
    margin-top: 32px;
    .title-frame {
      width: 100%;
      height: 60px;
      color: #ffffff;
      font-size: 24px;
      padding-top: 20px;
      // &::before {
      //   content: "";
      //   width: 10px;
      //   height: 10px;
      //   display: inline-block;
      //   border-radius: 50%;
      //   background: #65cac0;
      //   margin-right: 10px;
      // }
    }
    .aisle-frame {
      width: 100%;
      height: auto;
      .aisle-content {
        width: 222px;
        height: 68px;
        border-radius: 20px;
        color: rgba(255, 255, 255, 0.65);
        font-size: 28px;
        margin-right: 10px;
        margin-bottom: 15px;
        background-color: rgba(255, 255, 255, 0.15);
      }
      .aisle-content:nth-child(3n + 0) {
        margin-right: 0;
      }
      .aisle-true {
        background-image: linear-gradient(73deg, #fe7919 0%, #ab3fe7 100%);
        color: #ffffffff;
      }
    }
  }
}
// .content {
//   width: 300px;
//   height: 100px;
//   box-sizing: border-box;
//   padding: 5px;
//   border-radius: 5px;
//   background-image: -webkit-linear-gradient(left, red 0%, blue 30%, yellow 60%, green 90%);
// }
// .box {
//   width: 100%;
//   height: 100%;
//   border-radius: 5px;
//   background: #fff;
// }
</style>
